package com.lx.util.secure.algorithm.encrypt;

import com.lx.util.LX;
import com.lx.util.secure.algorithm.SecureAlgorithm;
import com.lx.util.secure.algorithm.coder.CoderType;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

public class Des extends SecureAlgorithm<Des> {


    @Override
    protected CoderType defaultKeyCoderType() {
        return CoderType.DEFAULT;
    }

    @Override
    protected CoderType defaultCoderType() {
        return CoderType.BASE64;
    }

    @Override
    protected String defaultEncryptAlgorithm() {
        return "DES/CBC/PKCS5Padding";
    }

    @Override
    public byte[] encrypt(byte[] bytes) {
        try{
            Key secretKey = generateKey(getKey());
            Cipher cipher = Cipher.getInstance(getEncryptAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(getIv()));
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] decrypt(byte[] bytes) {
        try{
            Key secretKey = generateKey(getKey());
            Cipher cipher = Cipher.getInstance(getEncryptAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(getIv()));
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static final String ALGORITHM = "DES";
    private static Key generateKey(byte[] key) throws Exception {
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }
}
